1. Introduction
The Module pattern helps us to split our code in multiple files and and avoid files with huge lines of code.
2. Learning Objectives
- Objective 1: To describe the module patter.
- Objective 2: To know the best practices of this module
3. Key Concepts
- it was implemented in ES2015
- We can split the function in other files and exported and imported
- To use ES2015 module use either:
.mjs
or add"type": "module"
to yourpackage.json
file. - We have private values when we don’t export variables inside our file.
The The module pattern allow us to split or code in multiples files to have our code organized, within our module we need to use the keyword
export
before any variable or function we want to use in other part of our app and use the keywordimport
to import the function previously exported. Also adds the capacity to have private functions and variables when we omit theexport
keyword in our module.
4. Examples and Practical Cases
- we can use the module pattern in practically all modern JS code
// index.js
import { sum, subtract, divide, multiply } from './math.js';
console.log('Sum', sum(1, 2));
console.log('Subtract', subtract(1, 2));
console.log('Divide', divide(1, 2));
console.log('Multiply', multiply(1, 2));
// math.js
export function sum(x, y) {
return x + y;
}
export function multiply(x, y) {
return x * y;
}
export function subtract(x, y) {
return x - y;
}
export function divide(x, y) {
return x / y;
}
{
"name": "node-starter",
"version": "0.0.0",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
}
}
5. Reflections and Synthesis
-
Summary:
It helps for example in firebase functions, they use the old syntax and adding the capacity to use modules it simplify our code.